import type { PageLoad } from './$types';
import * as commands from '$lib/commands'
import type { FudaHistory, FudaHistoryFilter, IpcResponse, ListParams } from '$lib/bindings';
export const load: PageLoad = async ({ url, route, params }) => {
    console.log("route=", route, " url=", url, " params=", params);
    const currentPage = parseInt(url.searchParams.get('page') || '1', 10) - 1; // Get the page parameter from the URL query
    const pageSize = 100
    console.log(`currentPage = ${currentPage} `)


    try {

        // Define the argument
        const args: ListParams<FudaHistoryFilter> = {
            page: currentPage,
            size: pageSize,
            filter: null,
        }

        const res: IpcResponse<FudaHistory[]> = await commands.list_history(args)

        if (res.error) {
            // If the response status is not OK, throw an error
            throw new Error(`(history/+page.ts) Server returned an error: ${res.error}`);
        }

        console.log("(history/+page.ts) res=", res);

        // If the server response is empty, return sample data
        if (res.result) {
            return {
                currentPage: currentPage,
                pageSize: pageSize,
                history: res.result.data
            };
        }

        return {
            currentPage: currentPage,
            pageSize: pageSize,

            history: []
        };
    } catch (error) {
        // If there's any error (e.g., network issue), return sample data
        console.error('Error fetching history:', error);
        return {
            currentPage: currentPage,
            pageSize: pageSize,

            history: []
        };
    }

};